package com.seven.restaurant.util;

import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * FTP服务器工具类
 * @author BaiBan
 * @since 2022/6/27
 */

@Setter
@Log4j2
@Configuration
@ConfigurationProperties("ftp")
public class FTPUtil {

    private String host;

    private Integer port;

    private String username;

    private String password;

    /**
     * 选择要上传的文件 上传到FTP服务器中
     * @param file 要上传的文件
     * @param FTP_BASEPATH 要上传的文件夹的路径名 保存在FTPPaths中
     * @return 如果正常运行返回上传的文件名 失败返回Null
     */
    public String uploadFile(MultipartFile file, String FTP_BASEPATH) {

        // 获取上传的文件流
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 获取上传的文件名
        String originalFilename = file.getOriginalFilename();

        // 截取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 使用UUID拼接后缀 定义一个不重复的文件名
        String fileName = UUID.randomUUID() + suffix;

        FTPClient ftp = new FTPClient();

        try {
            int reply;
            ftp.connect(host, port); // 连接FTP服务器
            ftp.login(username, password); // 登录
            reply = ftp.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return null;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.makeDirectory(FTP_BASEPATH);
            ftp.enterLocalPassiveMode();
            ftp.changeWorkingDirectory(FTP_BASEPATH);
            ftp.storeFile(fileName,inputStream);
            inputStream.close();
            ftp.logout();

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if(ftp.isConnected()) {

                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return "http://114.116.112.52:8080/data/" + FTP_BASEPATH + "/" + fileName;
    }
}
